package com.hengby.hengcrud.core.util;

import com.hengby.hengcrud.core.exception.HengCrudException;
import com.hengby.hengcrud.core.exception.HengCrudExceptionEnum;
import com.hengby.hengcrud.modular.base.tips.SuccessTips;
import com.hengby.hengcrud.modular.base.tips.Tips;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.UUID;

public class FileUtil {

    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * NIO way
     */
    public static byte[] toByteArray(String filename) {

        File f = new File(filename);
        if (!f.exists()) {
            log.error("文件未找到！" + filename);
            throw new HengCrudException(HengCrudExceptionEnum.FILE_NOT_FOUND);
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            throw new HengCrudException(HengCrudExceptionEnum.FILE_READING_ERROR);
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                throw new HengCrudException(HengCrudExceptionEnum.FILE_READING_ERROR);
            }
            try {
                fs.close();
            } catch (IOException e) {
                throw new HengCrudException(HengCrudExceptionEnum.FILE_READING_ERROR);
            }
        }
    }

    /**
     * 删除目录
     *
     * @author fengshuonan
     * @Date 2017/10/30 下午4:15
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 生成Excel文件
     *
     * @param filename 文件名称
     * @param list     文件内容List
     * @param clazz    List中的对象类型
     * @return ResponseBo
     */
    public static Tips createExcelByPOIKit(String filename, List<?> list, Class<?> clazz) {
        if (list.isEmpty()) {
            throw new HengCrudException(HengCrudExceptionEnum.EXPORT_DATA_IS_EMPTY);
        } else {
            boolean operateSign = false;
            String fileName = filename + ".xlsx";
            fileName = makeFileName(fileName);
            try {
                File fileDir = new File("file");
                if (!fileDir.exists()) {
                    fileDir.mkdir();
                }
                String path = "file/" + fileName;
                FileOutputStream fos;
                fos = new FileOutputStream(path);
                operateSign = ExcelUtils.$Builder(clazz)
                        // 设置每个sheet的最大记录数,默认为10000,可不设置
                        // .setMaxSheetRecords(10000)
                        .toExcel(list, "查询结果", fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (operateSign) {
                return new SuccessTips();
            } else {
                throw new HengCrudException(HengCrudExceptionEnum.EXPORT_EXCEL_ERROR);
            }
        }
    }

    /**
     * 生成Csv文件
     *
     * @param filename 文件名称
     * @param list     文件内容List
     * @param clazz    List中的对象类型
     * @return ResponseBo
     */
    public static Tips createCsv(String filename, List<?> list, Class<?> clazz) {

        if (list.isEmpty()) {
            throw new HengCrudException(HengCrudExceptionEnum.EXPORT_DATA_IS_EMPTY);
        } else {
            boolean operateSign;
            String fileName = filename + ".csv";
            fileName = makeFileName(fileName);

            File fileDir = new File("file");
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            String path = "file/" + fileName;
            operateSign = ExcelUtils.$Builder(clazz)
                    .toCsv(list, path);
            if (operateSign) {
                return new SuccessTips();
            } else {
                throw new HengCrudException(HengCrudExceptionEnum.EXPORT_CSV_ERROR);
            }
        }
    }

    /**
     * 文件名加UUID
     *
     * @param filename 文件名
     * @return UUID_文件名
     */
    private static String makeFileName(String filename) {
        return UUID.randomUUID().toString() + "_" + filename;
    }
}